<template>
  <a-modal v-model:visible="addCodeTable1" :title="codeDialogName1" :width="800" @ok="handleOk()" @Cancel="handleCancel()">
    <a-form ref="addCodeForm" :model="formState" name="basic" :label-col="{ span: 3 }" :wrapper-col="{ span: 20 }" autocomplete="off">
      <a-form-item label="码表名称" name="codesName" :rules="rules">
        <a-input v-model:value="formState.codesName" placeholder="请输入标准中文名称" />
      </a-form-item>

      <a-form-item label="码表说明" name="codesMsg"> <a-input v-model:value="formState.codesMsg" placeholder="请输入标准说明" /> </a-form-item>
      <a-form-item label="编码配置" name="codepeizhi" :rules="[{ required: true, message: '编码配置不能为空' }]">
        <a-button class="editable-add-btn" style="margin-bottom: 8px" @click="handleAdd">添加</a-button>
        <!-- 编码配置表格 -->
      </a-form-item>
      <!-- <a-form-item label="" :wrapper-col="{ span: 24 }" name="codepeizhi"> -->
      <!-- <a-button class="editable-add-btn" style="margin-bottom: 8px" @click="handleAdd">添加</a-button> -->
      <!-- 编码配置表格 -->
      <a-form ref="form1" :model="editableData">
        <a-table bordered :data-source="dataSource" :columns="columns">
          <template #bodyCell="{ column, text, record }">
            <template v-if="column.dataIndex !== 'operation'">
              <div class="editable-cell">
                <!-- <a-form ref="form1" :model="record"> -->
                <!-- <a-form-item>
                    <a-input
                      v-if="editableData[record.configsId]"
                      v-model:value="editableData[record.configsId][column.dataIndex]"
                      :rules="[{ required: true, message: `${column.dataIndex}不能为空` }]"
                      style="margin: -5px 0"
                    />

                  </a-form-item> -->

                <template v-if="editableData[record.configsId]">
                  <a-form-item v-if="column.dataIndex == 'configsValue'" :name="column.dataIndex" :rules="tableColumnValueRules">
                    <a-input v-model:value="editableData[record.configsId][column.dataIndex]" style="margin: -5px 0" />
                  </a-form-item>
                  <a-form-item v-else-if="column.dataIndex == 'configsName'" :name="column.dataIndex" :rules="tableColumnNameRules">
                    <a-input v-model:value="editableData[record.configsId][column.dataIndex]" style="margin: -5px 0" />
                  </a-form-item>
                  <a-form-item v-else :name="column.dataIndex">
                    <a-input v-model.trim:value="editableData[record.configsId][column.dataIndex]" style="margin: -5px 0" />
                  </a-form-item>
                </template>

                <template v-else>
                  {{ text }}
                </template>
                <!-- </a-form> -->
              </div>
            </template>
            <template v-else>
              <div class="editable-row-operations">
                <span v-if="editableData[record.configsId]">
                  <a-typography-link @click="save(record)">保存&nbsp;</a-typography-link>
                  <a-popconfirm title="确定取消?" @confirm="cancel(record.configsId)">
                    <a>取消 </a>
                  </a-popconfirm>
                </span>
                <span v-else>
                  <!-- {{record}} -->
                  <a @click="edit(record.configsId)">修改 </a>
                </span>
                <a-popconfirm v-if="dataSource.length" title="Sure to delete?" @confirm="props.dialogStatue === 'add' ? onDelete(record.configsId) : onEditDelete(record.configsId)">
                  <a>删除</a>
                </a-popconfirm>
              </div>
            </template>
          </template>
        </a-table>
      </a-form>
      <!-- </a-form-item> -->
    </a-form>
  </a-modal>
</template>
<script setup lang="ts">
  import { addList, modifyList, searchList, delData, addData } from '@/api/test/api';
  import { computed, reactive, ref, watch } from 'vue';
  import { CheckOutlined, EditOutlined } from '@ant-design/icons-vue';
  import { cloneDeep } from 'lodash-es';
  import type { Ref, UnwrapRef } from 'vue';
  import { message } from 'ant-design-vue';
  // import { Form } from 'ant-design-vue';

  // const useForm = Form.useForm;
  const props = defineProps({
    dataList: {
      type: Object,
      default: () => {
        return {};
      },
    },
    addCodeTable: {
      type: Boolean,
      default: false,
    },
    dialogStatue: {
      type: String,
    },
    codeDialogName: {
      type: Boolean,
    },
    newData: {
      type: String,
      // default: () => [],
    },
  });
  //弹窗状态
  //   let dialogStatue = ref<string>('');
  const emit = defineEmits(['changeShow', 'editSuccessed']);
  const addCodeTable1 = ref<boolean>(false);
  const editableData1 = ref<boolean>(false);
  const codeDialogName1 = ref<string>('');
  watch(
    () => props.addCodeTable,
    (nvalue: boolean) => {
      addCodeTable1.value = nvalue; //开关弹窗
      if (nvalue == false) {
        return;
      }
      if (props.dialogStatue == 'add') {
        codeDialogName1.value = '新增码表';
        formState.codesId = '';
        formState.codesMsg = '';
        formState.codesName = '';
      } else {
        codeDialogName1.value = '编辑码表';
        formState.codesMsg = props.dataList.codesMsg;
        formState.codesName = props.dataList.codesName;
        formState.codesId = props.dataList.codesId;
        let codesNo = props.dataList.codesId;
        const ressearchList = searchList({ codesNo });
        console.log(ressearchList);
        // dataSource.value = ressearchList.data;
      }
      console.log(props.newData, 'jjjjjj');
    },
  );
  // 检查名字是否重复
  const NameValidator = (_rule: any, value: string, callback: any) => {
    if (value) {
      let nameLength = 0;
      if (props.newData?.split(',').indexOf(value) !== undefined) {
        nameLength = props.newData?.split(',').indexOf(value);
      }
      if (nameLength == -1) {
        return Promise.resolve();
      } else {
        return new Promise((resolve, reject) => {
          reject('码表名称不能重复');
        });
      }
    } else {
      return Promise.resolve();
    }
  };
  // 表单校验规则
  const rules = [
    { required: true, message: '不能为空!', trigger: ['blur', 'change'] },
    { pattern: /^[\u4e00-\u9fa5_a-zA-Z0-9]+$/, message: '必须为汉字或字母组成', trigger: ['blur', 'change'] },
    { validator: NameValidator, trigger: ['blur', 'change'] },
  ];
  // 表单内的表格字段校验规则
  const tableColumnValueRules = [
    { required: true, message: '不能为空!', trigger: ['blur', 'change'] },
    { pattern: /^\S*$/, message: '不能包含空格', trigger: ['blur', 'change'] },

    // { validator: NameValidator, trigger: ['blur', 'change'] },
  ];
  const tableColumnNameRules = [
    { required: true, message: '不能为空!', trigger: ['blur', 'change'] },
    // { pattern: /^\S*$/, message: '码值名称不能包含空格', trigger: ['blur', 'change'] },
    { pattern: /^[\u4e00-\u9fa5_a-zA-Z0-9]+$/, message: '必须为汉字或字母组成', trigger: ['blur', 'change'] },
    // { validator: NameValidator, trigger: ['blur', 'change'] },
  ];
  // 新增码表弹窗中的表格
  interface DataItem1 {
    // key: number;
    configsId: string;
    configsValue: number | null;
    configsName: string;
    configsMsg: string;
  }
  interface FormState {
    codesId: string;
    codesName: string;
    codesMsg: string;
    dataSource1: DataItem1[];
  }
  let formState = reactive<FormState>({
    codesId: '',
    codesName: '',
    codesMsg: '',
    dataSource1: [],
  });
  const columns = [
    {
      title: '码值取值',
      dataIndex: 'configsValue',
      width: '15%',
    },
    {
      title: '码值名称',
      dataIndex: 'configsName',
      width: '20%',
    },
    {
      title: '码值含义',
      dataIndex: 'configsMsg',
      width: '40%',
    },
    {
      title: '操作',
      dataIndex: 'operation',
      width: '20%',
    },
  ];
  let dataSource: Ref<DataItem1[]> = ref([]);
  formState.dataSource1 = dataSource;
  const count = computed(() => dataSource.value.length + 1);
  const editableData: UnwrapRef<Record<string, DataItem1>> = reactive({});
  const addCodeForm = ref();
  const handleOk = async () => {
    const result1 = addCodeForm.value.validate();
    await form1.value.validate();

    if (formState.codesName == '') {
      message.error('请填写码表名称');
      return;
    } else if (dataSource.value == []) {
      message.error('请添加码表配置');
    }
    let datas = {
      codesMsg: formState.codesMsg,
      codesName: formState.codesName,
      configsList: dataSource.value,
    };
    console.log(datas, '局部');
    emit('changeShow', 'false');
    addCodeTable1.value = false;
    editableData1.value = false;
    if (props.dialogStatue === 'add') {
      //新增
      const resAdd = await addList(datas);
      console.log(resAdd);
      //  emit('editSuccessed',datas)
    } else {
      // 编辑
      let arrData: any = [];
      dataSource.value.forEach(item => {
        arrData.push(item);
      });
      let editDatas = {
        codesId: formState.codesId,
        codesMsg: formState.codesMsg,
        codesName: formState.codesName,
        // configsList: JSON.parse(JSON.stringify(dataSource.value)),
        updateConfigDTO: arrData,
      };
      const resEdit = await modifyList(editDatas);
      emit('editSuccessed', editDatas);
      console.log(resEdit, '2222222222222222');
    }
  };
  const edit = (key: string) => {
    editableData[key] = cloneDeep(dataSource.value.filter(item => key === item.configsId)[0]);
  };

  const form1 = ref();
  // 保存时校验规则
  const save = async (record: any) => {
    // const ['form'+record.configsId] = '';
    // await form1.value.validate();
    // Object.assign(dataSource.value.filter(item => key === item.configsId)[0], editableData[key]);
    // delete editableData[key];
    // addFag = 0;
    console.log(editableData[record.configsId], '111111');
    if (editableData[record.configsId]['configsValue'] === null || String(editableData[record.configsId]['configsValue']) == '') {
      message.error('请填写码值取值！');
    } else if (editableData[record.configsId]['configsName'] === '') {
      message.error('请填写码值名称！');
    } else if (editableData[record.configsId]['configsValue'] !== null && editableData[record.configsId]['configsName'] !== '') {
      let tip = 0;
      // dataSource.value.forEach(item => {
      //   if (item.configsValue == configsValue) {
      //     tip += 1;
      //     message.error('码值取值重复');
      //   }
      //   if (item.configsName == editableData[key]['configsName']) {
      //     tip += 1;
      //     message.error('码值名称重复');
      //   }
      // });
      if (tip == 0) {
        Object.assign(dataSource.value.filter(item => record.configsId === item.configsId)[0], editableData[record.configsId]);
        delete editableData[record.configsId];
        let hh = { ...record, codesId: formState.codesId };
        console.log('hh', hh);
        const resAddTableData = await addData(hh);
        console.log(resAddTableData);
        addFag = 0;
      }
      // else{}
    }
    // Object.assign(dataSource.value.filter(item => key === item.configsId)[0], editableData[key]);
    // delete editableData[key];
    // addFag = 0;
  };
  // 删除
  const onDelete = (key: string) => {
    dataSource.value = dataSource.value.filter(item => item.configsId !== key);
    if (addFag == 1) {
      dataSource.value.pop();
      addFag = 0;
    }
  };
  const onEditDelete = (configsId: string) => {
    let data = {
      configsId: configsId,
    };

    delData(data).then(res => {
      dataSource.value = dataSource.value.filter(item => item.configsId !== configsId);
    });
  };
  // 随机生成数字
  let cg = () => {
    return Math.random() * 999;
  };
  // 是否添加了一个的信号
  let addFag = 0;
  const handleAdd = () => {
    console.log(dataSource.value);
    if (addFag == 1) {
      message.error('请新增完再添加下一条数据！');
      return;
    }
    const newData = {
      // key: '',
      configsId: `${cg()}`,
      configsValue: null,
      configsName: '',
      configsMsg: '',
    };
    dataSource.value.push(newData);
    addFag = 1;
    editableData[newData.configsId] = cloneDeep(dataSource.value.filter(item => newData.configsId === item.configsId)[0]);
  };
  const cancel = (key: string) => {
    if (addFag == 1) {
      dataSource.value.pop();
      addFag = 0;
    }
    delete editableData[key];
  };
  //调用弹窗的关闭按钮方法
  const handleCancel = () => {
    addCodeForm.value.clearValidate();
    form1.value.clearValidate();
    if (addFag == 1) {
      dataSource.value.pop();
      addFag = 0;
    }
    emit('changeShow', 'false');
  };
</script>
<style lang="less" scoped>
  // 新增码表弹窗
  .editable-cell {
    position: relative;

    .editable-cell-input-wrapper,
    .editable-cell-text-wrapper {
      padding-right: 24px;
    }

    .editable-cell-text-wrapper {
      padding: 5px 24px 5px 5px;
    }

    .editable-cell-icon,
    .editable-cell-icon-check {
      position: absolute;
      right: 0;
      width: 20px;
      cursor: pointer;
    }

    .editable-cell-icon {
      display: none;
      margin-top: 4px;
    }

    .editable-cell-icon-check {
      line-height: 28px;
    }

    .editable-cell-icon:hover,
    .editable-cell-icon-check:hover {
      color: #108ee9;
    }

    .editable-add-btn {
      margin-bottom: 8px;
    }
  }

  /deep/ .ant-table-thead > tr > th:not(.ant-table-cell:nth-child(3)):not(:last-child):not(.ant-table-selection-column):not(.ant-table-row-expand-icon-cell):not([colspan])::before {
    position: static;
    display: inline-block;
    margin-right: 8px;
    font-size: 14px;
    font-family: SimSun, sans-serif;
    color: #ff4d4f;
    content: '*';
    transform: translateY(0px);
  }
</style>
